package com.qingyun.common.controller;

import com.google.gson.Gson;
import com.qingyun.common.service.impl.QiniuService;

import com.qingyun.model.common.dtos.R;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/qiniu")
@Slf4j
public class QiniuController {

    @Autowired
    private QiniuService qiniuService;



    @RequestMapping(value="/uploadImg", method= RequestMethod.POST)
    @PermitAll
    public R uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {


        if(file.isEmpty()) {
            return R.error("文件为空，请重新上传");
        }

        try {
            String fileUrl=qiniuService.saveImage(file);

            return R.success(fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error("文件上传发生异常！");
    }
    @PostMapping("imgDel")
    public R videoImgDel(@RequestHeader("Img-Delete")String url){
        if(url.isEmpty()){
            return R.error("图片不存在！");
        }
        qiniuService.delete(url); //删除云服务器文件
        return R.success(null);
    }


    //七牛Token
    @GetMapping("/gettoken")
    @ResponseBody
    public R uptoken(){
        String token = qiniuService.getToken();
        return R.success(token);
    }
}

